/** 请求js */
let wcache = require("../utils/wcache.js");
var app = getApp();
var host = app.globalData.url;
// var token = wcache.get('token')
// if(!token){
//   token = wx.getStorageSync('token')
// }
//请求
function request(url, method,params, success, fail) {
  this.requestLoading(url, method, params, "", success, fail)
}
// 展示进度条的网络请求
// url:网络请求的url
// params:请求参数
// message:进度条的提示信息
// success:成功的回调函数
// fail：失败的回调
function requestLoading(url, method, params, message, success, fail) {
  wx.showNavigationBarLoading()
  var token = wcache.get('token')
  if (message != "") {
    wx.showLoading({
      title: message,
    })
  }
  wx.request({
    url: host+url,
    data: params,
    header: {
      'token': token,
      "Content-Type": "application/json", "Response-Type": "json"
    },
    method: method,
    success: function (res) {
      //console.log(res.data)
      wx.hideNavigationBarLoading()
      if (message != "") {
        wx.hideLoading()
      }
      if (res.data.code == 0) {
        success(res.data)
      } else if(res.data.code === 401) { // 401, token失效
        wx.redirectTo({
          url: '/pages/login/login'
        });
      }else if(res.data.code == 404){
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 2000
        });
      }else if (res.data.code == 500) {
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 2000
        });
      }else{
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 2000
        });
      }
    },
    fail: function (res) {
      wx.hideNavigationBarLoading()
      if (message != "") {
        wx.hideLoading()
      }
      fail()
    },
    complete: function (res) {

    },
  })
}
module.exports = {
  request: request,
  requestLoading: requestLoading
}